<?php

use Medoo\Medoo;
use QL\QueryList;

/**
 * http://docs.guzzlephp.org/en/stable/request-options.html#query
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;
$db = new Medoo($config);
$db->delete('tDealer', ['sBrand' => '讴歌']);
$client = new GuzzleHttp\Client();

$res = $client->get(
    'http://www.acura.com.cn/api/sitecore/Common/GetProvinceFilterByDealer'
);
$html = (string)$res->getBody();
$temp = json_decode($html, true);
$provinces = $temp['Data'];

function get_cities($province_id)
{
    global $client;

    $res = $client->post(
        'https://www.acura.com.cn/api/sitecore/Common/GetCityFilterByDealer',
        [
            'multipart' => [[
                'name' => 'provinceId',
                'contents' => $province_id,
            ]]
        ]);
    $html = (string)$res->getBody();

    $temp = json_decode($html, true);
    return $temp['Data'];
}


function get_dealers($city_id)
{
    global $client;

    $res = $client->get('https://www.acura.com.cn/api/sitecore/Map/GetDealerList',
        ['query' => ['cityId' => $city_id]]);
    $html = (string)$res->getBody();

    $temp = json_decode($html, true);
    return $temp['Data'];
}


foreach ($provinces as $p) {
    $province_id = $p['Id'];
    $province = $p['Name'];
    $cites = get_cities($province_id);
    foreach ($cites as $c) {
        $city_id = $c['Id'];
        $city = $c['Name'];
        $dealers = get_dealers($city_id);
        foreach ($dealers as $item) {

            $db->insert('tDealer', [
                'sDealerName' => $item['DEALER_NAME'],
                'nBrandID' => $item['DEALER_CODE'],
                'sBrand' => '讴歌',
                'sProvince' => $province,
                'sCity' => $city,
                'sAddress' => $item['ADDRESS'],
                'sSaleCall' => $item['SALES_PHONE'],
                'sLatitude' => $item['Lat'],
                'sLongitude' => $item['Lng'],
                'dUpdateTime' => Medoo::raw('now()'),
                'sManufacturer' => '讴歌',
            ]);
            echo "{$item['DEALER_NAME']}完成" . PHP_EOL;
        }
    }
}

echo '爬虫结束' . PHP_EOL;